Page({
  data: {
    detail: null
  },

  onLoad(options) {
    const { id } = options;
    if (!id) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      return;
    }
    this.fetchMedicineDetail(id);
  },

  // 获取药品详情
  fetchMedicineDetail(id) {
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: `YOUR_API_URL/medicine/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          const detail = this.formatDetailData(res.data.data);
          this.setData({
            detail
          });
        } else {
          this.useMockData(id);
        }
      },
      fail: () => {
        this.useMockData(id);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 格式化详情数据
  formatDetailData(data) {
    return {
      id: data.id,
      name: data.name,
      price: data.price.toFixed(2),
      isPrescription: data.isPrescription,
      specification: data.specification,
      indication: data.indication,
      usage: data.usage,
      images: data.images || [],
      detailImages: data.detailImages || [],
      details: data.details || []
    };
  },

  // 使用模拟数据
  useMockData(id) {
    const mockDetail = {
      id,
      name: '阿莫西林胶囊',
      price: 35.60,
      isPrescription: true,
      specification: '0.25g*20粒/盒',
      indication: '用于敏感菌所致的感染，如中耳炎、鼻窦炎、咽喉炎等。',
      usage: '口服。一次1-2粒，每6-8小时1次。',
      images: [
        'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
      ],
      detailImages: [
        'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
      ],
      details: [
        { label: '生产厂家', value: '某制药有限公司' },
        { label: '批准文号', value: 'H12345678' },
        { label: '贮藏条件', value: '密封，常温保存' },
        { label: '有效期', value: '24个月' }
      ]
    };

    const detail = this.formatDetailData(mockDetail);
    this.setData({
      detail
    });
  },

  // 图片加载失败处理
  onImageError(e) {
    const defaultImage = 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg';
    const type = e.currentTarget.dataset.type || 'slide';
    
    if (type === 'slide') {
      const index = e.currentTarget.dataset.index;
      this.setData({
        [`detail.images[${index}]`]: defaultImage
      });
    } else {
      const index = e.currentTarget.dataset.index;
      this.setData({
        [`detail.detailImages[${index}]`]: defaultImage
      });
    }
  },

  // 加入购物车
  onAddToCart() {
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success'
    });
  },

  // 立即购买
  onBuyNow() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 添加图片预览方法
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset;
    wx.previewImage({
      urls,
      current
    });
  }
}); 